package com.example.administrator.x2picturetransliteration.Http;


import com.example.administrator.x2picturetransliteration.Constants;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

/**
 * Http请求数据
 * 2018/10/9.
 */

public class HttpData {

    //网络请求延时时间
    private final int Timeout = 360;

    public HttpData(){

    }

    public BlogService getService(){
        return getRetrofit().create(BlogService.class);
    }

    private Retrofit getRetrofit(){

        OkHttpClient client = new OkHttpClient.Builder().
        addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {

                        System.out.println("------------http请求数据:" + message);
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BODY)).
                connectTimeout(Timeout, TimeUnit.SECONDS).
                readTimeout(Timeout, TimeUnit.SECONDS).
                addInterceptor(new TokenInterceptor()).
                writeTimeout(Timeout, TimeUnit.SECONDS).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.getConstants().getBaseUrl())
                .client(client)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit;
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

}
